package com.yanghongyue.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanghongyue.reggie.bean.*;
import com.yanghongyue.reggie.common.BaseContext;
import com.yanghongyue.reggie.common.CustException;
import com.yanghongyue.reggie.mapper.OrdersMapper;
import com.yanghongyue.reggie.service.AddressBookService;
import com.yanghongyue.reggie.service.CartService;
import com.yanghongyue.reggie.service.OrderDetailService;
import com.yanghongyue.reggie.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author HongyueYang
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private CartService cartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserServiceImpl userService;

    @Override
    public void saveOrder(Orders orders) throws CustException {

        //获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //获取当前用户购物车数据
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Cart> cartList = cartService.list(wrapper);

        //如果购物车没有数据，提示错误信息
        if (cartList == null || cartList.size() == 0) {
            throw new CustException("购物车为空，不能下单");
        }

        //根据用户id查询用户信息
        User user = userService.getById(userId);

        //根据地址id查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustException("地址信息有误，不能下单");
        }

        //生成一个订单号
        Long orderNumber = IdWorker.getId();

        //创建订单明细集合
        List<OrderDetail> detailList = new ArrayList<>();

        //定义存放的总金额对象
        AtomicInteger amount = new AtomicInteger(0);

        //遍历购物车集合
        for (Cart cart : cartList) {
            //创建订单明细对象
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(orderNumber);
            detail.setNumber(cart.getNumber());
            detail.setDishFlavor(cart.getDishFlavor());
            detail.setDishId(cart.getDishId());
            detail.setName(cart.getName());
            detail.setImage(cart.getImage());
            detail.setAmount(cart.getAmount());
            detail.setSetmealId(cart.getSetmealId());

            //将明细对象添加到明细集合
            detailList.add(detail);
            //计算总金额
            amount.addAndGet(cart.getAmount().multiply(new BigDecimal(cart.getNumber())).intValue());
        }

        //组装订单数据
        orders.setId(orderNumber);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setNumber(orderNumber + "");
        orders.setUserName(user.getName());
        orders.setUserId(userId);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());

        //向订单表插入数据
        this.save(orders);
        //向订单明细表插入数据
        orderDetailService.saveBatch(detailList);
        //清空购物车数据
        cartService.remove(wrapper);


    }


    //再来一单
    @Override
    public void again(Orders orders) {

        //根据订单id查询订单明细
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orders.getId());
        List<OrderDetail> detailList = orderDetailService.list(wrapper);

        //创建购物车集合
        List<Cart> cartList = new ArrayList<>();

        //遍历订单明细
        for (OrderDetail detail : detailList) {
            //创建购物车对象
            Cart cart = new Cart();
            BeanUtils.copyProperties(detail, cart);
            //给购物车对象设置id
            cart.setUserId(BaseContext.getCurrentId());
            //设置创建时间
            cart.setCreateTime(LocalDateTime.now());
            //将购物车对象添加到购物车集合
            cartList.add(cart);
        }
        //将购物车集合插入到购物车表
        cartService.saveBatch(cartList);

    }
}
